package com.gzx.qc.api;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import vip.xiaonuo.common.exception.CommonException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class AiScannerApi {

    private static final String BASE_URL = "https://ark.cn-beijing.volces.com/api/v3";

    public static List<String> callRemoteApi(String userMessage,String modelId,String bearer) throws IOException {
        // 创建 OkHttpClient.Builder 实例并设置超时时间
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        // 设置连接超时时间为 60 秒
        builder.connectTimeout(60, java.util.concurrent.TimeUnit.SECONDS);
        // 设置读取超时时间为 60 秒
        builder.readTimeout(60, java.util.concurrent.TimeUnit.SECONDS);
        // 设置写入超时时间为 65 秒
        builder.writeTimeout(65, java.util.concurrent.TimeUnit.SECONDS);

        // 使用 builder 构建 OkHttpClient 实例
        OkHttpClient client = builder.build();
        JSONObject payload = new JSONObject();
        try {
            payload.put("model", modelId);
            // 创建消息列表
            List<Map<String, Object>> messagesList = new ArrayList<>();
            Map<String, Object> message = new HashMap<>();
            message.put("role", "user");
            message.put("content", userMessage);
            messagesList.add(message);
            // 创建 JSONArray 来存储消息对象
            JSONArray messagesJsonArray = new JSONArray();
            for (Map<String, Object> msg : messagesList) {
                JSONObject msgJson = new JSONObject(msg);
                //messagesJsonArray.put(msgJson);
                messagesJsonArray.add(message);
            }
            // 创建 payload
            //JSONObject payload = new JSONObject();
            payload.put("messages", messagesJsonArray);
        }catch (Exception e){
            log.info("发生异常了，一场信息为{}",e.getMessage());
        }
        RequestBody body = RequestBody.create(payload.toString(), MediaType.get("application/json"));
        Request request = new Request.Builder()
                .url(BASE_URL + "/chat/completions")
                .addHeader("Authorization", "Bearer " + bearer)
                .addHeader("Content-Type", "application/json")
                .post(body)
                .build();
//        log.info("本次请求的请求头为:{}请求体为:{}", request.headers(), payload.toString());
        long begin = System.currentTimeMillis();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                log.info("response.body().string() = " + response.body().string());
                throw new CommonException("发生异常： " + response);
            }
            String responseBody = response.body().string();
            log.info("本次调用接口返回的结果为{}",responseBody);
            try {
                //JSONObject jsonResponse = new JSONObject(responseBody);
                JSONObject jsonResponse =JSONObject.parseObject(responseBody);
                ArrayList<String> result = new ArrayList<>();
                result.add(jsonResponse.getJSONArray("choices").getJSONObject(0).getJSONObject("message").getString("content"));
                result.add(jsonResponse.getJSONArray("choices").getJSONObject(0).getJSONObject("message").getString("reasoning_content"));
                return result;
            }catch (Exception e){
                log.error("发生异常了{}",e.getMessage());
            }
        }
        long end = System.currentTimeMillis();
        long l = end - begin;
        log.info("本次接口调用一共花费："+l+"毫秒");
        return new ArrayList<>();
    }
}
